package com.huluobo.sign.pages

import android.util.Log
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.lib_base.BaseLoadingDialog
import com.huluobo.lib_base.BaseTitle
import com.huluobo.lib_base.RoutePath
import com.huluobo.lib_base.UIState
import com.huluobo.sign.SignIntent
import com.huluobo.sign.SignViewModel
import com.huluobo.sign.entity.SignEntity
import com.huluobo.sign.entity.SignEntityItem
import com.king.ultraswiperefresh.UltraSwipeRefresh
import com.king.ultraswiperefresh.rememberUltraSwipeRefreshState
import kotlinx.coroutines.launch

/**
 *  Created by LC on 2025/8/23.
 */

@Composable
fun SignListPage(navHostController: NavHostController, vm: SignViewModel = hiltViewModel()) {
    val list = remember {
        SnapshotStateList<SignEntityItem>()
    }

    var isShowProgress by remember {
        mutableStateOf(false)
    }

    //刷新框架的状态
    var state = rememberUltraSwipeRefreshState()

    //刷新的页码
    var page by remember {
        mutableStateOf(1)
    }

    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect {
                when (it) {
                    is UIState.OnFailed -> {
                        isShowProgress = false
                        ToastUtils.showLong("获取签到列表失败:${it.msg}")
                        Log.e("TagA", "获取签到列表失败:${it.msg}")
                    }

                    UIState.OnLoading -> {
                        isShowProgress = true
                    }

                    is UIState.OnSuccess<*> -> {
                        isShowProgress = false
                        if (page == 1) {
                            list.clear()
                        }
                        list.addAll(it.data as SignEntity)
                    }
                }
            }
        }
        vm.sendIntent(SignIntent.GetAllSigns("1", "10"))
    })

    //当刷新框架的状态是刷新的时候会触发该位置
    LaunchedEffect(key1 = state.isRefreshing, block = {
        if (state.isRefreshing) {
            page = 1
            vm.sendIntent(SignIntent.GetAllSigns("$page", "10"))
            state.isRefreshing = false
        }
    })

    //当刷新框架的状态是读取时,会触发该位置
    LaunchedEffect(key1 = state.isLoading, block = {
        if (state.isLoading) {
            page++
            vm.sendIntent(SignIntent.GetAllSigns("$page", "10"))
            state.isLoading = false
        }
    })

    if (isShowProgress) {
        BaseLoadingDialog()
    }

    Scaffold(
        bottomBar = {
            Button(
                onClick = {
                    navHostController.navigate(RoutePath.SIGN_COMMIT)
                }, modifier = Modifier
                    .fillMaxWidth()
                    .padding(10.dp)
            ) {
                Text(text = "签到")
            }
        }
    ) {
        Column(
            modifier = Modifier
                .padding(it)
                .padding(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp)
        ) {
            BaseTitle(title = "考勤打卡", navHostController = navHostController)
            Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                val week = TimeUtils.getChineseWeek(System.currentTimeMillis())
                Text(text = "时间 $week")
                Text(text = "考勤规则")
            }
            Spacer(modifier = Modifier.height(10.dp))
            UltraSwipeRefresh(state = state, onRefresh = {
                state.isRefreshing = true
            }, onLoadMore = {
                state.isLoading = true
            }) {
                LazyColumn(
                    content = {
                        items(list) {
                            SignItem(signEntityItem = it)
                        }
                    },
                    verticalArrangement = Arrangement.spacedBy(10.dp),
                    modifier = Modifier.fillMaxWidth()
                )
            }
        }
    }
}

@Composable
fun SignItem(signEntityItem: SignEntityItem) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .border(1.dp, Color.LightGray, RoundedCornerShape(10.dp))
            .padding(10.dp),
        colors = CardDefaults.cardColors(
            containerColor = Color.White
        )
    ) {
        Column(verticalArrangement = Arrangement.spacedBy(5.dp)) {
            Text(text = "签到信息")
            Text(text = "经纬度 : ", fontSize = 11.sp, color = Color.LightGray)
            Text(
                text = "经度 : ${signEntityItem.lat} , 维度 : ${signEntityItem.lon}",
                fontSize = 11.sp,
                color = Color.LightGray
            )
            Text(text = "打卡类型 : ${signEntityItem.type}")
            Text(text = "打卡状态 : ${signEntityItem.status}")
            Text(text = "打卡地点 : ${signEntityItem.address}")
            Text(text = "打卡时间 : ${signEntityItem.createTime}")
        }
    }
}